var url = document.location.toString();
var arrUrl = url.split("//");
var start = arrUrl[1].indexOf("/");
var relUrl = arrUrl[1].substring(0, start);
//判断发票类型是否有值，如果有不让操作人员选

$("#personalHead").bind("click", function () {
    if ($(this).prop("checked") == true) {
        $("#invoiceTitle-search").attr("style", "display:none");
    }
})
$("#companyHead").bind("click", function () {
    if ($(this).prop("checked") == true) {
        $("#invoiceTitle-search").attr("style", "display:blcok");
    }
})

function GetRequest() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

var Request = new Object();
Request = GetRequest();
//--------------------------------模糊搜索项目begin--------------------------------------
var currentData = new Map();
var id;
//实现搜索功能
$("#invoiceTitle-search").click(function () {
    inputChange();
})
//1：搜索数据
var inputChange = function () {
    var inputValue = $("#invoiceTitle").val();
    if (inputValue != "") {
        $.ajax({
            url: '/invoice/title',
            type: 'post',
            async: true,
            data: {
                "companyName": inputValue,
                "taxId": ""
            },
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded',
            success: function (data) {
                console.log(data);
                if (data != "fail") {
                    _initItems(data);
                }
            },
            error: function () {
                // alert("操作失败");
            }
        })
    }
};
var maxFontNumber = 0;//最大字数
var suggestContainer = $('<div></div>'); //创建一个子<ul>
suggestContainer.attr('id', "testInput-suggest");
suggestContainer.attr('tabindex', '0');
suggestContainer.hide();

//2：初始化搜索到的数据进行显示
var _initItems = function (items) {
    // $('#ruleOrgCode').val("");
    // currentData.clear()
    suggestContainer.empty();
    for (var i = 0; i < items.length; i++) {
        if (items.length > maxFontNumber) {
            maxFontNumber = items.length;
        }
        var suggestItem = $('<div></div>'); //创建一个子<li>
        suggestItem.attr('id', items[i].taxId);
        id = items[i].taxId;
        currentData.set(items[i].taxId, items[i]);
        suggestItem.append(items[i].name);
        suggestItem.css({
            'width': '100%',
            'padding': '10px',//item间距
            'word-wrap': 'break-word',
            'word-break': 'normal',
            'cursor': 'pointer',
            'background-color': '#ffffff',//默认背景颜色
            'color': '#000000',//默认字体颜色
            'text-align': 'left',
            'border-bottom': '1px solid rgb(204,204,204)'
        });
        suggestItem.bind("mouseover",
            function () {
                $(this).css({
                    'background-color': '#eeeeee',//选中背景颜色
                    'color': '#000000'//选中字体颜色
                });
            });
        suggestItem.bind("mouseout",
            function () {
                $(this).css({
                    'background-color': '#ffffff',//默认背景颜色
                    'color': '#000000'//默认字体颜色
                });
            });
        suggestItem.bind("click", showClickTextFunction);//选中后处理数据
        //suggestItem.bind("click", itemSelectFunction);
        suggestItem.appendTo(suggestContainer);
        suggestContainer.appendTo(document.body);
    }
    suggestContainer.removeAttr("style");
    suggestContainer.css({
        'border': '1px solid #ccc',
        'max-height': '200px',
        'top': $('#invoiceTitle').offset().top + $('#invoiceTitle').outerHeight(),
        'left': $('#invoiceTitle').offset().left + 6,
        'width': $('#invoiceTitle').width() + 7,//获取项目的宽度加上边框边距
        'position': 'absolute',
        'font-size': '12px',//默认字体大小
        'font-family': 'Arial',
        'z-index': 99999,
        'background-color': '#EEE',
        'overflow-y': 'auto',
        'overflow-x': 'hidden',
        'paddding-left': '0!important',
        'margin-left': '0!important'

    });
    maxFontNumber = 0;
    suggestContainer.show();
};

//3.选中后处理数据
var showClickTextFunction = function () {
    FillAll(this.id);
    $('#invoiceTitle').val(this.id);
    $('#invoiceTitle').val(this.innerText);
    // $('#ruleOrgCode').val(this.getAttribute("Id"));
    suggestContainer.hide();
};

//4.点击空白地方 隐藏
$(document).bind("click", function (e) {
    var target = $(e.target);
    if (target.closest(".pop").length == 0) {
        suggestContainer.hide();
    }
})
//-------------------------模糊搜索项目end------------------------------------------------

//------------------填充数据开始---------------------------
var choseId;

function FillAll(id) {
    if (currentData.size != 0) {
        var obj = currentData.get(id);
        choseId = id;
        $("#taxId").val(obj.taxId);
        $("#bankType").val(obj.bank);
        $("#textBankNo").val(obj.bankAccount);
        $("#cityAddress").val(obj.location);
        $("#phoneNumber").val(obj.fixedPhone);
    }
}

//------------------填充数据结束---------------------------

//----------------点击开票按钮------------------------
$("#submit-invoice").click(function () {
    //防止重复点击按钮
    $(this).attr('disabled', 'disabled').die('click');
    //===1,调用CallOut_invOpenOut开票接口
    //获取电子邮件
    var invEmail = $("#inv-email").val();
    //获取手机号
    var invPhone = $("#inv-phone").val();
    //获取发票类型值
    var invoiceTypeCode;//发票类型
    if (typeof $('input:radio[name="invoiceType"][checked]').val() == "undefined") {
        alert("请选择发票类型!");
        return;
    } else {
        invoiceTypeCode = $('input:radio[name="invoiceType"][checked]').val();
    }
     //电子票需要填写邮箱或者电话
    if (invoiceTypeCode == '026' && (invEmail == undefined || invEmail == '') ) {
       if(invPhone == undefined || invPhone == ''){
           alert("请刷新一下页面，填写接收电子票的邮箱或者手机号！");
           return;
       }
    }
    var obj = currentData.get(choseId);
    var invoiceTitle;
    var blueRedType;
    var taxId;
    var fixedPhone;
    var bankAccount;
    var buyerName;
    if (obj == undefined) {
        invoiceTitle = $("#invoiceTitle").val();
        blueRedType = $("#blueRedType").val();
        taxId = $("#taxId").val();
        fixedPhone = $("#cityAddress").val() + $("#phoneNumber").val();
        bankAccount = $("#bankType").val() + $("#textBankNo").val();
        buyerName = $("#invoiceTitle").val();
    }else{
         invoiceTitle = $("#invoiceTitle").val();
         blueRedType = $("#blueRedType").val();
         //taxId = obj.taxId;
         //fixedPhone = obj.location + obj.fixedPhone;
        // bankAccount = obj.bank + obj.bankAccount ;
        // buyerName = obj.name;
        taxId = $("#taxId").val();
        fixedPhone = $("#cityAddress").val() + $("#phoneNumber").val();
        bankAccount = $("#bankType").val() + $("#textBankNo").val();
        buyerName = $("#invoiceTitle").val();
    }

    if ($('input:radio[name="invoiceHead"][checked]').val() == 0) {
        $.ajax({
            url: '/invoice/openByCompany',
            type: 'post',
            async: true,
            data: JSON.stringify({
                "guid": Request["invoiceId"],
                "buyerTaxNo": taxId,
                "buyerName": buyerName,
                "buyerAddressPhone": fixedPhone,
                "buyerBankAccount": bankAccount,
                "buyerEmail": invEmail,
                "invoiceTypeCode": invoiceTypeCode,
                "buyerPhone": invPhone
            }),
            dataType: 'json',
            contentType: 'application/json;charset=utf-8',
            beforeSend: function () {
                //等待友好提示
                showLoadding($("#submit-invoice"));
            },
            success: function (data) {
                //等待友好提示
                showLoadding($("#submit-invoice"));
                window.open(arrUrl[0] + "//" + relUrl + "/invoice/openInv" + "?invoiceId=" + Request["invoiceId"] + "&blueRedType=" + blueRedType, "_self");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                var obj = JSON.parse(XMLHttpRequest.responseText);
                alert(obj.message);
                window.open(arrUrl[0] + "//" + relUrl + "/invoice/openInv" + "?invoiceId=" + Request["invoiceId"] + "&blueRedType=" + blueRedType, "_self");

            }
        })
    } else {
        $.ajax({
            url: '/invoice/openByPerson',
            type: 'post',
            async: true,
            data: JSON.stringify({
                "guid": Request["invoiceId"],
                "buyerName": invoiceTitle,
                "buyerEmail": invEmail,
				"buyerPhone": invPhone,
                "invoiceTypeCode": invoiceTypeCode
            }),
            dataType: 'json',
            contentType: 'application/json;charset=utf-8',
            beforeSend: function () {
                //等待友好提示
                showLoadding($("#submit-invoice"));
            },
            success: function (data) {
                //等待友好提示
                showLoadding($("#submit-invoice"));
                window.open(arrUrl[0] + "//" + relUrl + "/invoice/openInv" + "?invoiceId=" + Request["invoiceId"] + "&blueRedType=" + blueRedType, "_self");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                var obj = JSON.parse(XMLHttpRequest.responseText);
                alert(obj.message);
                window.open(arrUrl[0] + "//" + relUrl + "/invoice/openInv" + "?invoiceId=" + Request["invoiceId"] + "&blueRedType=" + blueRedType, "_self");
            }
        })
    }
})